# 自定义异常处理
from rest_framework.exceptions import ValidationError
from rest_framework.views import exception_handler
from rest_framework.views import Response
from rest_framework import status


def custom_exception_handler(exc: ValidationError, context):
    # 先调用REST framework默认的异常处理方法获得标准错误响应对象
    print(exc, 1, type(exc))
    response = exception_handler(exc, context)
    print(type(response), response)
    if response is None:
        # return Response({
        #     'message': '服务器错误:{exc}'.format(exc=exc)
        # }, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)
        return Response({
            'message': '服务器错误 十分抱歉'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)

    else:
        if isinstance(response, Response):
            try:
                message = exc.detail if isinstance(exc.detail, str) else (list(dict(exc.detail).values())[0][0] if isinstance(list(dict(exc.detail).values())[0], list) else list(dict(exc.detail).values())[0])
                code = exc.get_codes() if isinstance(exc.get_codes(), str) else (list(dict(exc.get_codes()).values())[0][0] if isinstance(list(dict(exc.get_codes()).values())[0], list) else list(dict(exc.get_codes()).values())[0])
            except Exception:
                message = exc.detail[0]
                code = response.status_code
            print(message, code)
            print(0)
        else:
            try:
                # {'password': [ErrorDetail(string='密码格式不正确 1111', code=3001)]}
                code_ = list(dict(exc.detail).values())[0]
                message = code_[0]
                code = list(dict(exc.get_codes()).values())[0][0]
                print(1)
            except:
                # [ErrorDetail(string='此密码不匹配', code=3002)]
                message = exc.detail[0]
                code = exc.get_codes()[0]
                print(2)
        return Response({
            'message': message,
            'code': code
        }, status=response.status_code, exception=True)
